package com.ruoyi.web.controller.initData;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.dao.SysDeptDao;
import com.ruoyi.system.domain.dao.SysRoleDao;
import com.ruoyi.system.mapper.OaMapper;
import com.ruoyi.system.mapper.SysDeptDaoMapper;
import com.ruoyi.system.mapper.SysRoleDaoMapper;
import com.ruoyi.system.mapper.SysRoleDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class Role2DeptInit {

    @Autowired
    private OaMapper oaMapper;
    @Resource
    private SysRoleDaoMapper sysRoleDaoMapper;
    @Resource
    private SysDeptDaoMapper sysDeptDaoMapper;
    @Resource
    private SysRoleDeptMapper sysRoleDeptMapper;

    /**
     * 绑定 角色 到 部门
     */
    public void bindRole2Dept() {
        List<SysRoleDao> roleList = sysRoleDaoMapper.selectList(new LambdaQueryWrapper<>());
        if (roleList != null && roleList.size() > 0) {
            roleList.stream().forEach(item -> {
                if (StringUtils.isEmpty(item.getOldData())) {
                    return;
                }
                String[] split = item.getOldData().split(",");
                if (split.length > 1) {
                    String roleUuid = split[0].split("=")[1];
                    String dutyUuid = split[1].split("=")[1];

                    List<Map<String, String>> maps = oaMapper.listDataByCondition("ent_t_duty", "ent_t_duty_uuid", dutyUuid);
                    if (maps==null||maps.size()==0) {
                        return;
                    }
                    LambdaQueryWrapper lw = new LambdaQueryWrapper<SysDeptDao>()
                            .likeRight(SysDeptDao::getOldData, String.format("depUuid=%s", maps.get(0).get("ent_t_dep_uuid")));
                    SysDeptDao sysDept = sysDeptDaoMapper.selectOne(lw);
                    if (sysDept != null) {
                        SysRoleDept sysRoleDept = new SysRoleDept();
                        sysRoleDept.setRoleId(item.getRoleId());
                        sysRoleDept.setDeptId(sysDept.getDeptId());
                        sysRoleDeptMapper.batchRoleDept(Arrays.asList(sysRoleDept));
                    }
                }
            });
        }
    }
}
